﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Presenter.DocumentsTemplate;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.WP.Layouts.MS.InformationManagement.WP
{
    public partial class DocumentsTemplateCreation : LayoutsPageBase, IDocumentsTemplateView
    {

        #region fields

        DocumentsTemplatePresenter _presenter;

        #endregion

        #region Properties

        public SPFile NewDocument { get; set; }

        public Dictionary<int, string> Templates { get; set; }

        public string NewDocumentName { get { return txtNewFileName.Text + lblExtension.Text; } }

        public int TemplateId { get { return int.Parse(ddlTemplates.SelectedValue); } }

        #endregion

        #region Form Methods

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new DocumentsTemplatePresenter(this);
            if (IsPostBack) return;
            _presenter.HandleLoad();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ddlTemplates.Required(ExceptionConstants.ERROR_DDL_OBLIGATORIO, AjaxControlToolkit.ValidatorCalloutPosition.Right);
            txtNewFileName.Required(ExceptionConstants.ERROR_CAMPO_NULO, AjaxControlToolkit.ValidatorCalloutPosition.Right);
        }

        protected void Selected_Template(object sender, EventArgs e)
        {
            if (ddlTemplates.Text.Split('.').Length > 0)
                lblExtension.Text = "." + ddlTemplates.SelectedItem.Text.Split('.')[ddlTemplates.SelectedItem.Text.Split('.').Length - 1];
            else
                lblExtension.Text = string.Empty;
        }

        protected void Action_Generar(object sender, EventArgs e)
        {
            _presenter.HandleCreateNewDocument();
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            ddlTemplates.DataSource = Templates;
            ddlTemplates.DataBind();
            ddlTemplates.Items.Insert(0,new ListItem() { Value = "0", Text = GlobalConstants.DDL_INITIAL_TEMPLATE });
        }

        public new event Presenter.Support.Events.ErrorHandler OnError;

        public event Presenter.Support.Events.SuccessHandler OnSuccess;

        #endregion

        public void ShowCreatedFile()
        {
            NewDocument.Item.Update();
            Response.Redirect(SPContext.Current.Web.Lists[GlobalConstants.LIST_BIBLIOTECA_USUARIO].DefaultEditFormUrl + "?ID=" + NewDocument.Item.ID.ToString() + "&ContentTypeId=0x010100107533981D2A472FAC06AD46D58AEDBB008333296263CB465FAC51B677D9FDC74B", true);
        }
    }
}
